from odoo import fields, models, api, _
from odoo.exceptions import UserError


class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    # 备料数量
    s_pm_quantity = fields.Float('Preparation Quantity', digits='Product Unit of Measure', readonly=True, copy=False)
    s_prepared_materials = fields.Boolean('Prepared materials', readonly=True, copy=False)
    s_pm_notes = fields.Text('Preparation Notes', readonly=True, copy=False)

    def action_select_sale_material_preparation(self):
        order_line = self.filtered(lambda x: x.product_id.detailed_type == 'product')
        if not order_line:
            raise UserError(_('There are no products available for preparation'))
        return {
            'name': _('material preparation'),
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'res_model': 's.sale.order.material.preparation.wizard',
            'target': 'new',
        }

    def action_cancel_sale_material_preparation(self):
        ...

    def write(self, vals):
        if 'product_uom_qty' in vals:
            product_uom_qty = vals.get('product_uom_qty')

            for line in self:
                msg = _('Change in sales order quantity, %d -> %d \n', line.product_uom_qty, product_uom_qty)
                if line.s_pm_quantity > 0:
                    line.s_pm_notes = (line.s_pm_notes or '') + msg

        return super().write(vals)